#include "cutil.h"
#include "wspaceview.h"
#include "ui_wspaceview.h"

/**
    @file wspaceview.cpp
    @author Claus Wimmer
    @date 2013-07-16

    Project: secondspace
    Licence: LGPL (Lesser GPL)
*/

// Parent widget is the application window class.
WSpaceView::WSpaceView(QWidget *parent) : QWidget(parent), _mousePressed(false), _logo(":/biglogo.png"), _image(0), ui(new Ui::WSpaceView), _fileindex(0){
    ui->setupUi(this);
    this->_logo = this->_logo.scaled(CUtil::pixwidth, CUtil::pixheight);
    this->_image = &_logo;
    // Set window attributes for a pure image display.
    this->setAutoFillBackground(false);
    this->setAttribute(Qt::WA_NoSystemBackground);
    this->setAttribute(Qt::WA_OpaquePaintEvent, true);
    this->setMinimumSize(CUtil::pixwidth * CUtil::zoom, CUtil::pixheight * CUtil::zoom);
    this->setMaximumSize(CUtil::pixwidth * CUtil::zoom, CUtil::pixheight * CUtil::zoom);
    this->show();
}

WSpaceView::~WSpaceView() {
    delete ui;
}

// Raised by zspace.h everey four space calculation steps.
void WSpaceView::imageReady() {
    repaint();
    CUtil::saveImageFile(_image, _fileindex++);
}

void WSpaceView::paintEvent(QPaintEvent *) {
    if(0 != _image){
        const QRect src = _image->rect(), dst = this->rect();
        QPainter _painter;
        _painter.begin(this);
        _painter.drawImage(dst, *_image, src, Qt::ColorOnly);
        _painter.end();
    }
}

void WSpaceView::setImage(QImage *image) {
    this->_image = image;
}

// Notify the kernels about the new mouse position.
void WSpaceView::mousePressEvent(QMouseEvent *_evt) {
    this->_mousePressed = true;
    emit mousePointed((uint)_evt->x(), (uint)_evt->y());
}

// Prepare drag obervation.
void WSpaceView::mouseReleaseEvent(QMouseEvent *) {
    this->_mousePressed = false;
}

// Notify the kernels but only while dragging.
void WSpaceView::mouseMoveEvent(QMouseEvent *_evt) {
    if(this->_mousePressed){
        emit mousePointed((uint)_evt->x(), (uint)_evt->y());
    }

}

// Show the last mouse click position as a tooltip of this widget.
QPoint WSpaceView::mousePos() {
    QCursor c = cursor();
    QPoint p = mapFromGlobal(c.pos());
    if(0 > p.x() || 0 > p.y() || size().width() <= p.x() || size().height() <= p.y()) {
        return QPoint(-1, -1);
    }
    return p;
}

void WSpaceView::wheelEvent(QWheelEvent *) {
    timeout();
}
